<div class="article">
  <!-- 按钮 -->
  <div class="btns" style="margin-bottom: 10px;">
    <button type="button" id='add_btn' class="btn btn-primary">新增</button>
    <button type="button" id='batch_btn' class="btn btn-danger">批量删除</button>
    <input type="text" class="form-control" style="width: 30%;display: inline-block;" id="search_title" placeholder="请输入文章标题">
    <select class="form-control" id="search_article_parentId"  style="width: 30%;display: inline-block;" placeholder="请选择文章类型">
        <option value=""></option>
    </select>
    <button type="button"  id='search_btn' class="btn btn-primary">搜索</button>
  </div>
  <!-- 表格 -->
  <table class="table">
      <thead>
        <tr>
          <th scope="col">编号</th>
          <th scope="col">文章标题</th>
          <th scope="col">发布时间</th>
          <th scope="col">审核状态</th>
          <th scope="col">所属栏目</th>
          <th scope="col">文章封面</th>
          <th scope="col">操作</th>
        </tr>
      </thead>
      <tbody>
        
      </tbody>
  </table>
  <!-- 详情 -->
  <div class="modal fade" id="articleDetailsModal" tabindex="-1" role="dialog" aria-labelledby="articleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
            <h5 class="modal-title" id="articleModalLabel">Modal title</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            </div>
            <div class="modal-body">
              
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
  </div>
  <!-- 新增模态框 -->
  <div class="modal fade" id="articleAddModal" tabindex="-1" role="dialog" aria-labelledby="articleModalLabel_publish" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="articleModalLabel_publish">新增文章</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form>
                  <input type="text" style="display: none;" id="article_id" >
                    <div class="form-group">
                      <label for="article_title">文章标题</label>
                      <input type="email" class="form-control" id="article_title" aria-describedby="emailHelp">
                    </div>
                    <div class="form-group">
                        <label for="article_parentId">所属栏目</label>
                        <select class="form-control" id="article_parentId">
                          <option value=""></option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="article_source">文章封面</label>
                        <input type="hidden" id="imagepath" name="">  <!-- 保存的图片id 用于表单提交 -->
                        <span id="upload_duixiang">上传</span><!-- 上传按钮 -->
                        <div class="show"></div>
                    </div>
                    <div class="form-group">
                        <label for="article_content" id="article_content_label">文章内容</label>
                        
                        <div id="editor"></div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" id='save_btn' class="btn btn-primary">保存</button>
            </div>
        </div>
    </div>
  </div>
  <!-- 分页 -->
  <div id="myPage" class="demo"></div>
</div>
<script>
  // 全局变量区域
  var article_src;
  var token = localStorage.getItem('token');
  var baseUrl = 'http://47.100.58.59:7788';
  var allData;
  articlesPageQuery(1);
  findAllCategories();
    $.ajaxSetup({
        headers:{
            'Authorization':token
        }
    })

  // 时间戳转日期格式
  function timestampToTime(timestamp) {
    var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    Y = date.getFullYear() + '-';
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    D = date.getDate() + ' ';
    h = date.getHours() + ':';
    m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()) : date.getMinutes()) + ':';
    s = (date.getSeconds() < 10 ? '0'+(date.getSeconds()) : date.getSeconds());
    return Y+M+D+h+m+s;
  }
  
  // 1.分页查询文章信息
  function articlesPageQuery(page){
    $.ajax({
      url:baseUrl + '/article/pageQuery',
      method:'get',
      data:{
        page:page,
        pageSize:5
      },
      headers: {'Authorization':token},
      success:function(res){
        $('tbody').empty(); // 加载之前，清空tbody
        // 动态渲染表格信息
        res.data.list.forEach(function(item){
          var timestamp = item.publishTime;
          var publishTime = timestampToTime(timestamp);
          $(`
            <tr>
              <td><input type="checkbox" value="`+item.id+`"></td>
              <td>`+item.title+`</td>
              <td>`+publishTime+`</td>
              <td>`+item.status+`</td>
              <td>`+item.category.name+`</td>
              <td><img style="width:50px;height:50px;" src="`+item.source+`" alt="图片丢失"></td>
              <td>
                <span class="btn_del">删除</span>
                <span class="btn_edit">修改</span>
                <span class="btn_detail">详情</span>
              </td>
            </tr>
          `).appendTo($('tbody'))
        })
        // 初始化分页插件
        $("#myPage").sPage({
          page: res.data.page, //当前页码              
          pageSize: 5, //每页显示多少条数据，默认10条               
          total: res.data.total, //数据总条数,后台返回              
          backFun: function(page) { //点击分页按钮回调函数，返回当前页码                    
            articlesPageQuery(page);
          }
        });
        allData = res.data
      }
    })
  }

  // 2.点击新增按钮，打开模态框
  $('#add_btn').click(function(){
    // 清空表单
    $('#article_id').val('');
    $('#article_title').val('');
    $('#editor').empty();
    // 清空上传插件
    $('.show').empty();
    // 初始化图片上传工具
    a = $("#upload_duixiang").FraUpload({
        view        : ".show",      // 视图输出位置
        url         : "http://134.175.100.63:5588/file/upload", // 上传接口
        fetch       : "img",   // 视图现在只支持img
        debug       : false,    // 是否开启调试模式
        /* 外部获得的回调接口 */
        onLoad: function(e){                    // 选择文件的回调方法
            console.log("外部: 初始化完成...");
        },
        breforePort: function (e) {         // 发送前触发
            console.log("文件发送之前触发");
        },  
        successPort: function (e) {         // 发送成功触发
            console.log("文件发送成功");
            onload_image()
        },
        errorPort: function (e) {       // 发送失败触发
            console.log("文件发送失败");
            onload_image()
        },
        deletePost: function(e){    // 删除文件触发
            console.log("删除文件");
            console.log(e);
            alert('删除了'+e.filename)
            onload_image()
        },
        sort: function(e){      // 排序触发
            console.log("排序");
            onload_image()
        },
    });

    // 获取图片上传信息
    function onload_image(){
        var res = a.FraUpload.show()
        var ids = [];
        for(let k in res){
            this_val = res[k]
            if(!empty(res[k]['is_upload']) && !empty(res[k]['ajax'])){
                ajax_value = res[k]['ajax'];
                ids.push(ajax_value.data.id)
            }
        }
        $("#imagepath").val(ids);
        article_src = res[0].ajax.data.id
        console.log(article_src);
    }

    /**
     * 判断变量是否为空
     */
    function empty(value) {
        if(value=="" || value==undefined || value==null || value==false || value==[] || value=={}){
            return true;
        }else{
            return false;
        }
    }
    // 初始化富文本编辑器
    var E = window.wangEditor;
    var editor = new E('#editor');
    editor.create();
    // 打开模态框
    $('#articleAddModal').modal('show');
  })

  // 3.点击保存按钮
  $('#save_btn').click(function(){
    // 获取表中的数据
    var id = $('#article_id').val();
    var title = $('#article_title').val();
    var categoryId = $('#article_parentId').val();
    var content = $('.w-e-text').html();
    var data;
    if(id){
      data = {
        id,
        title,
        categoryId,
        content,
        source:'http://134.175.100.63:8686/group1/'+article_src
      }
    } else {
      data = {
        title,
        categoryId,
        content,
        source:'http://134.175.100.63:8686/group1/'+article_src
      }
    }
    if(title && categoryId && content){
      $.ajax({
        url:baseUrl + '/article/saveOrUpdate',
        method:'post',
        data:data,
        success:function(res){
          articlesPageQuery(1);
          $('#articleAddModal').modal('hide');
          alert(res.message);
        }
      })
    } else {
      alert('请输入完整的数据！')
    }

  })
  
  // 4.点击详情按钮
  $('tbody').on('click','.btn_detail',function(){
    id = $(this).closest('tr').find('input[type=checkbox]').val();
    $.ajax({
      url:baseUrl + '/article/findById',
      method:'get',
      headers:{'Authorization':token},
      data:{id:id},
      success:function(res){
        $('#articleModalLabel').text(res.data.title);
        $('#articleDetailsModal .modal-body').html(res.data.content);
        $('#articleDetailsModal').modal('show');
      }
    })
  })
  // 5.点击修改按钮
  $('tbody').on('click','.btn_edit',function(res){
    $('.show').empty();
    // 初始化富文本编辑器
    a = $("#upload_duixiang").FraUpload({
        view        : ".show",      // 视图输出位置
        url         : "http://134.175.100.63:5588/file/upload", // 上传接口
        fetch       : "img",   // 视图现在只支持img
        debug       : false,    // 是否开启调试模式
        /* 外部获得的回调接口 */
        onLoad: function(e){                    // 选择文件的回调方法
            console.log("外部: 初始化完成...");
        },
        breforePort: function (e) {         // 发送前触发
            console.log("文件发送之前触发");
        },  
        successPort: function (e) {         // 发送成功触发
            console.log("文件发送成功");
            onload_image()
        },
        errorPort: function (e) {       // 发送失败触发
            console.log("文件发送失败");
            onload_image()
        },
        deletePost: function(e){    // 删除文件触发
            console.log("删除文件");
            console.log(e);
            alert('删除了'+e.filename)
            onload_image()
        },
        sort: function(e){      // 排序触发
            console.log("排序");
            onload_image()
        },
    });

    // 获取图片上传信息
    function onload_image(){
        var res = a.FraUpload.show()
        var ids = [];
        for(let k in res){
            this_val = res[k]
            if(!empty(res[k]['is_upload']) && !empty(res[k]['ajax'])){
                ajax_value = res[k]['ajax'];
                ids.push(ajax_value.data.id)
            }
        }
        $("#imagepath").val(ids);
        article_src = res[0].ajax.data.id
        console.log(article_src);
    }

    /**
     * 判断变量是否为空
     */
    function empty(value) {
        if(value=="" || value==undefined || value==null || value==false || value==[] || value=={}){
            return true;
        }else{
            return false;
        }
    }
    // 初始化富文本编辑器
    var E = window.wangEditor;
    var editor = new E('#editor');
    editor.create();
    
        $('#articleAddModal').modal('show');
        var id = $(this).closest('tr').find('input[type=checkbox]').val();
        // console.log(id)
        var a = allData.list.filter(function(res){
            return res.id == id;
        });
        // console.log(a[0].id)
        $('#article_id').val(a[0].id);
        $('#article_title').val(a[0].title);
        $('#article_parentId').val(a[0].categoryId);
        $('.w-e-text').html(a[0].content);
        // $('.FraUpload_imglist').
        // $('.w-e-text').html(a[0].content);
        var newImg = $('<li></li>').html($('<img src="'+a[0].source+'">'))
        $('.FraUpload_imglist').append(newImg);
    })
    // 6.点击删除按钮
  $('tbody').on('click','.btn_del',function(res){
        var id = $(this).closest('tr').find('input[type=checkbox]').val();
        var result = confirm('确认删除？');
        if(result){
          $.ajax({
            url: baseUrl + '/article/deleteById',
            method: 'get',
            data: {id:id},
            headers:{'Authorization':token},
            success: function(res){
              // 成功删除后，重载数据
              articlesPageQuery(1);
              // 提示删除成功
              alert(res.message);
            }
          })
        } else {
          alert('取消删除');
        }
        // console.log(allData);
        // var a = allData.list.filter(function(res){
        //     return res.id == id;
        // });
        // $('#article_title').val(a[0].title);
        // $('#article_parentId').val(a[0].categoryId);
        // $('.w-e-text').html(a[0].content);
        // // $('.w-e-text').html(a[0].content);
        // var newImg = $('<li></li>').html($('<img src="'+a[0].source+'">'))
        // $('.FraUpload_imglist').append(newImg);
    })
  // 7.搜索
  $('#search_btn').click(function(){
            var categoryId = $('#search_article_parentId').val();
            var title = $('#search_title').val();
            // console.log(categoryId,title)
            $.get('http://47.100.58.59:7788/article/pageQuery',
            {page:1,
            pageSize:3,
            title:title,
            categoryId:categoryId
            },function(res){
                $('tbody').empty()
                console.log(res)
            res.data.list.forEach(function(item){
                var newTr = $(`
                    <tr>
                        <td><input type="checkbox" value="`+item.id+`"></td>
                        <td>`+item.title+`</td>
                        <td>`+(item.source?`<img style="width:40px;height:40px" src="`+item.source+`" alt="">`:'暂无')+`</td>
                        <td>`+timestampToTime(item.publishTime)+`</td>
                        <td>`+item.category.name+`</td>
                        <td>
                            <span class='delete_btn'>删除</span>
                            <span class='edit_btn'>修改</span>
                            <span class='detile_btn'>详情</span>
                        </td>
                    </tr>
                `)
                $('tbody').append(newTr)
            })
            })
        })
    // 获取栏目信息
  function findAllCategories(){
    $.ajax({
      url: baseUrl + '/category/findAll',
      method: 'get',
      headers: {'Authorization':token},
      success: function(res){
        // 清空父栏目id单选框
        $('#article_parentId').empty();
        // 追加子栏目节点到父栏目单选框
        res.data.forEach(function(item){
          $(`<option value="`+item.id+`">`+item.name+`</option>`).appendTo($('#article_parentId'))
        })
        res.data.forEach(function(item){
                var newOption = $(`
                    <option value="`+item.id+`">`+item.name+`</option>
                `)
                $('#search_article_parentId').append(newOption)
            })
        
      }
    })
  }
</script>


